package cn.lg.soar.system.auth.controller;

import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.exceptions.PermissionException;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.ManyToManyDTO;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.core.util.easyexcel.ExcelUtil;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.database.util.MpSqlUtils;
import cn.lg.soar.database.util.PageUtils;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.api.manager.AccountManager;
import cn.lg.soar.system.api.model.UserCreateDTO;
import cn.lg.soar.system.auth.entity.User;
import cn.lg.soar.system.auth.model.*;
import cn.lg.soar.system.auth.service.IUserService;
import cn.lg.soar.system.auth.service.UserOrgService;
import cn.lg.soar.system.auth.service.UserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Api(tags = "用户管理")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/user")
public class UserController extends BaseController<User, IUserService> {

    @Override
    protected Serializable getId(User entity) {
        return entity.getId();
    }

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserOrgService userOrgService;
    @Autowired
    private AccountManager accountManager;

    private final static String SUBJECT = "用户";

    @Log(value = "新增" + SUBJECT, data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @CreateMapping
    public HttpResult<Serializable> create(@RequestBody UserCreateDTO data) {
        return HttpResult.<Serializable>success("创建用户成功")
                .setData(this.service.create(data));
    }

    @Log(value = "修改" + SUBJECT, data = "#p0", dataId = "#p0.id")
    @UpdateMapping
    public HttpResult<Void> update(@RequestBody @Validated User data) {
        User user = service.getById(data.getId());
        this.adminPermission(user.getUsername());
        return super.updateResult(data);
    }

    @Log(value = "修改用户状态", data = "#p0", type = Log.Type.TEXT)
    @ApiOperation("修改用户状态")
    @PostMapping(path = "update-status", name = "修改用户状态")
    public HttpResult<Void> updateStatus(@RequestBody @Validated UserStatusVo data) {
        Set<Long> ids = data.getIds();
        for (Long id : ids) {
            User user = service.getById(id);
            this.adminPermission(user.getUsername());
        }
        this.service.updateStatus(data.getStatus(), data.getIds());
        return HttpResult.success("修改用户状态成功");
    }

    @Log(value = "修改密码", data = "#p0.ids", type = Log.Type.TEXT)
    @ApiOperation("修改密码")
    @PostMapping(path = "update-password", name = "修改密码")
    public HttpResult<Void> updatePassword(@RequestBody @Validated UserPasswordDto data) {
        Set<Long> ids = data.getIds();
        for (Long id : ids) {
            User user = service.getById(id);
            this.adminPermission(user.getUsername());
        }
        this.service.updatePassword(data.getPassword(), data.getIds());
        return HttpResult.success("修改密码成功");
    }

    @Log(value = "重置密码", data = "#p0", type = Log.Type.TEXT)
    @ApiOperation("重置密码")
    @PostMapping(path = "reset-password", name = "重置密码")
    public HttpResult<Void> resetPassword(@RequestBody Set<Long> ids) {
        for (Long id : ids) {
            User user = service.getById(id);
            this.adminPermission(user.getUsername());
        }
        this.service.resetPassword(ids);
        return HttpResult.success("重置密码成功");
    }

    @Log(value = "删除" + SUBJECT, data = "#p0", type = Log.Type.TEXT)
    @RemoveMapping
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            User user = service.getById(id);
            this.adminPermission(user.getUsername());
        }
        return super.removeResult(ids);
    }

    @DetailMapping
    public HttpResult<UserDetailVo> detail(@Id Long id) {
        return HttpResult.data(this.service.detail(id));
    }

    @QueryMapping
    public HttpResult<PageResult<User>> query(PageQuery pageQuery, UserQuery query){
        QueryWrapper<User> wrapper = getFilter(query);
        IPage<User> page = service.page(PageUtils.toPage(pageQuery), wrapper);
        return HttpResult.data(PageUtils.toPageResult(page));
    }

    @ExistMapping
    public HttpResult<Boolean> exist(UserQuery query){
        QueryWrapper<User> wrapper = getFilter(query);
        return HttpResult.data(service.exist(wrapper));
    }

    @Log(value = "导出" + SUBJECT, data = "#p0")
    @ExportMapping
    public void exports(UserQuery query, HttpServletResponse resp) throws IOException {
        QueryWrapper<User> wrapper = getFilter(query);
        List<User> list = service.list(wrapper);
        // 导出
        ExcelUtil.exportExcel(UserController.SUBJECT, list, resp);
    }

    @Log(value = "导入" + SUBJECT)
    @ImportMapping
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @ApiOperation("清空缓存")
    @PostMapping(value = "clear-cache", name = "清空缓存")
    public HttpResult<Void> clearCache(long userId){
        this.service.clearCache(userId);
        return HttpResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Log(value = "设置用户角色")
    @ApiOperation("设置用户角色")
    @PostMapping(value = "set-role-ids")
    public HttpResult<Void> setRoleIds(@RequestBody @Validated ManyToManyDTO<Long, Long> dto){
        List<Long> bIds = dto.getBids();
        for (Long aId : dto.getAids()) {
            User user = service.getById(aId);
            this.adminPermission(user.getUsername());
            userRoleService.setUserRole(aId, bIds);
        }
        return HttpResult.success();
    }

    @ApiOperation("获取用户角色id")
    @GetMapping(value = "get-role-ids")
    public HttpResult<List<Long>> getRoleIds(@RequestParam Long userId){
        List<Long> ids = userRoleService.getRoleIds(userId);
        return HttpResult.data(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Log(value = "设置用户部门")
    @ApiOperation("设置用户部门")
    @PostMapping(value = "set-orgs")
    public HttpResult<Void> setOrg(@RequestBody @Valid UserOrgVO dto){
        List<Long> userIds = dto.getUserIds();
        List<UserOrgItemVO> orgs = dto.getOrgs();
        for (Long userId : userIds) {
            User user = service.getById(userId);
            this.adminPermission(user.getUsername());
            userOrgService.setUserOrg(userId, orgs);
        }
        return HttpResult.success();
    }

    @ApiOperation("获取用户部门id")
    @GetMapping(value = "get-orgs")
    public HttpResult<List<UserOrgItemVO>> getOrgs(@RequestParam Long userId){
        List<UserOrgItemVO> orgs = userOrgService.getOrgs(userId);
        return HttpResult.data(orgs);
    }

    private QueryWrapper<User> getFilter(UserQuery query) {
        QueryWrapper<User> wrapper = new SqueryWapper<>(User.class).listWrapper(query);
        Integer currentTenantId = UserContext.getUserOrDef().getCurrentTenantId(0);
        if (Objects.equals(currentTenantId, 0)) {
            MpSqlUtils.handleInOrEq(query.getTenantIds(), (sql, value) -> {
                wrapper.exists("select * from lg_sys_tenant_user r where lg_sys_user.id=r.user_id and r.tenant_id " + sql, value);
            });
        } else {
            wrapper.exists("select * from lg_sys_tenant_user r where lg_sys_user.id=r.user_id and r.tenant_id =" + currentTenantId);
        }

        MpSqlUtils.handleInOrEq(query.getRoleIds(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_role r where lg_sys_user.id=r.user_id and r.role_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(query.getOrgIds(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_org o where lg_sys_user.id=o.user_id and o.org_id " + sql, value);
        });
        MpSqlUtils.handleInOrEq(query.getPostIds(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_org p where lg_sys_user.id=p.user_id and p.post_id " + sql, value);
        });
        MpSqlUtils.handleLikeStr(query.getAccount(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_account_bind p where lg_sys_user.id=p.user_id and p.account " + sql, value);
        });
        return wrapper;
    }


    /**
     * 需要超级管理员权限
     * @param targetUsername
     */
    private void adminPermission(String targetUsername) {
        // 只有超级管理员可以改超级管理员的密码
        if (service.isSuperAdministrator(targetUsername) && !accountManager.isSuperAdministrator()) {
            throw new PermissionException(I18n.build("需超级管理员权限"));
        }
    }
}
